package org.macpro.alone.server.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.macpro.alone.prisist.domain.AloneUser;
import org.macpro.alone.server.common.database.DataComplexQueryManagerInter;
import org.macpro.alone.server.domain.PageDomain;
import org.macpro.alone.server.domain.SqlDomain;
import org.macpro.alone.server.domain.SqlDomain.LimitDomain;
import org.macpro.alone.server.framework.base.AloneBeanFactory;

/**
 * 结果集帮助类
 * 
 * @author 王东
 * 
 */
public class PageDomainHandle {
	/**
	 * 将于类相关的结果集合转换为一个String数组
	 * 
	 * @param pagedomain
	 * @return
	 */
	public static List<Map<String, String>> getStringArrayForPageDomain(
			PageDomain pagedomain) {
		if(pagedomain==null||pagedomain.getTotalResourtSize()<=0||pagedomain.resourtList==null)return new ArrayList<Map<String, String>>();
		List<Object> list = pagedomain.resourtList;
		if(list.get(0) instanceof Map){
			return (List)list;
		}
		List<Map<String, String>> listreturn = new ArrayList<Map<String, String>>();
		Class class_;
		Field[] field;
		if (list.size() > 0) {
			class_ = list.get(0).getClass();
			field = class_.getDeclaredFields();
			for (Object obj : list) {
				Map<String, String> map=new HashMap<String, String>();
				for(Field field_:field){
					try {
						Method method= class_.getMethod("get"+turnFirstToUp(field_.getName()));
						Object objr= method.invoke(obj);
						map.put(field_.getName().toUpperCase(), (String)objr);
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				listreturn.add(map);
			}
		}
		return listreturn;
	}
	public static String turnFirstToUp(String str){
		String str1=str.substring(0,1);
		String str2=str.substring(1);
		//	System.out.println(turnFirstToUp("wangdong"));
		return str1.toUpperCase()+str2;
	}
	public static void main(String[] args) {
		DataComplexQueryManagerInter dqm = (DataComplexQueryManagerInter) AloneBeanFactory
				.getBean("COMPLET_QUERY_ALONE_COMMON");
		PageDomain page = new PageDomain(0);
		List<LimitDomain> limitList = new ArrayList<LimitDomain>();
		// limitList.add(new LimitDomain("","",""));
		SqlDomain sqldomain = new SqlDomain("alone_user", "id", "asc",
				limitList);
		page = dqm.runComplexQuery(page, new AloneUser(), sqldomain);
	    List<Map<String, String>> list=	getStringArrayForPageDomain(page);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Map<String, String> name = (Map<String, String>) iterator.next();
			System.out.println(name.get("NAME"));
		}
	}
}
